Vue.component('lazy-img', {
    template: "<img :src='url'>",
    props: {
        src: {
            type: String,
            required: false,
            default: () => {
                return this.url;
            }
        },
    }, 
    data() {
        return {
            url: 'loading.gif'
        }
    },
    watch: {
        src: {
            immediate: true,
            handler() {
                this.url = 'loading.gif'
                var newImg = new Image()
                newImg.src = this.src
                newImg.onerror = () => {
                    newImg.src = this.url
                }
                newImg.onload = () => {
                    this.url = newImg.src
                }
            }
        }
    },
    mounted() {

    }
})


new Vue({
    el: '#app',
    data() {
        return {
            types: [
                'DEFAULT', 'CHINESE', 'NUMBER', 'NUMBER_ZH_CN', 'NUMBER_ZH_HK', 'WORD', 'WORD_LOWER',
                'WORD_UPPER', 'WORD_NUMBER_LOWER', 'WORD_NUMBER_UPPER', 'ARITHMETIC', 'ARITHMETIC_ZH'
            ],
            fonts: ['Actionj', 'Fresnel', 'Kaiti', 'Prefix', 'Ransom', 'Scandal', 'Epilog', 'Headache', 'Lexo', 'Progbot', 'Robot'],
            groupCaptchas: [],
            textBold: true,
            isDarkMode: true,
            selectedConfig: null,
            configJson: '',
            curlCommand: '',
            httpRequest: '',
            captchaImageUrl: '',
            testCaptchaUrl: '',
            captchaId: '',
            testCaptchaId: '',
            validateCode: '',
            validateResult: null
        }
    },
    mounted() {
        this.generate()
        // 从 localStorage 读取主题偏好
        const savedTheme = localStorage.getItem('theme')
        if (savedTheme) {
            this.isDarkMode = savedTheme === 'dark'
        }
        // 应用主题（包括默认主题）
        this.applyTheme()
    },
    methods: {
        handleChange() {
            this.generate()
        },
        toggleTheme() {
            this.applyTheme()
            // 保存主题偏好
            localStorage.setItem('theme', this.isDarkMode ? 'dark' : 'light')
        },
        applyTheme() {
            if (this.isDarkMode) {
                document.body.classList.remove('light-mode')
                document.body.classList.add('dark-mode')
            } else {
                document.body.classList.remove('dark-mode')
                document.body.classList.add('light-mode')
            }
        },
        generate() {
            let id = 0

            this.groupCaptchas = []
            for (let i = 0; i < this.types.length; i++) {
                let typeCaptchas = {
                    type: this.types[i],
                    captchas: []
                }
                for (let j = 0; j < this.fonts.length; j++) {
                    let isSupport = this.isSupport(this.types[i], this.fonts[j])
                    typeCaptchas.captchas.push({
                        type: this.types[i],
                        font: this.fonts[j],
                        url: `captcha/dynamic?id=${++id}&type=${this.types[i]}&font=${this.fonts[j]}&textBold=${this.textBold}&t=${new Date}`,
                        isSupport: isSupport
                    })
                }
                this.groupCaptchas.push(typeCaptchas)
            }
        },
        isSupport(type, font) {
            //类型为中文，仅支持Kaiti
            if ((type === 'CHINESE' || type === 'NUMBER_ZH_CN' || type === 'NUMBER_ZH_HK' || type === 'ARITHMETIC_ZH') && font !== 'Kaiti') return false
            // 其他个例
            if (type === 'ARITHMETIC' && font === 'Fresnel') return false
            if (type === 'ARITHMETIC' && font === 'Ransom') return false
            if (type === 'ARITHMETIC' && font === 'Progbot') return false

            return true
        },
        async showConfig(captcha) {
            try {
                // 获取配置信息
                const response = await fetch(`captcha/config?type=${captcha.type}&font=${captcha.font}&textBold=${this.textBold}`)
                const config = await response.json()

                this.selectedConfig = captcha
                this.configJson = JSON.stringify(config, null, 2)

                // 生成验证码
                await this.generateCaptcha(captcha)

            } catch (error) {
                console.error('获取配置失败:', error)
            }
        },
        async generateCaptcha(captcha) {
            // 生成新的验证码URL（添加时间戳确保每次都是新图片）
            const timestamp = new Date().getTime()
            this.captchaId = `demo_${timestamp}`

            // 使用dynamic接口，显示用户选择的类型和字体，同时这个ID也用于校验
            this.captchaImageUrl = `captcha/dynamic?id=${encodeURIComponent(this.captchaId)}&type=${captcha.type}&font=${captcha.font}&textBold=${this.textBold}&_t=${timestamp}`

            // 生成请求示例（基于dynamic接口）
            const baseUrl = window.location.origin
            const apiUrl = `${baseUrl}/captcha/dynamic?id=${encodeURIComponent(this.captchaId)}&type=${captcha.type}&font=${captcha.font}&textBold=${this.textBold}`

            // cURL命令
            this.curlCommand = `curl -X GET "${apiUrl}" \\
  -H "Accept: image/gif" \\
  --output captcha.gif`

            // HTTP请求原文
            this.httpRequest = `GET /captcha/dynamic?id=${this.captchaId}&type=${captcha.type}&font=${captcha.font}&textBold=${this.textBold} HTTP/1.1
Host: ${window.location.host}
Accept: image/gif
User-Agent: Mozilla/5.0
Connection: keep-alive

注意:
- 此接口使用 CaptchaServiceBuilder 创建独立实例
- 配置参数: type=${captcha.type}, font=${captcha.font}, textBold=${this.textBold}
- 由于使用独立缓存，此验证码无法通过 /captcha/validate 接口校验
- 如需测试校验功能，请使用注入实例的接口（见下方说明）`

            // 自动生成测试验证码（使用注入实例，可以校验）
            this.testCaptchaId = `test_${timestamp}`
            this.testCaptchaUrl = `captcha/demo?id=${encodeURIComponent(this.testCaptchaId)}&_t=${timestamp}`

            // 重置验证结果
            this.validateCode = ''
            this.validateResult = null

            // 预加载图片，确保验证码已生成
            await this.preloadCaptchaImage()
        },
        preloadCaptchaImage() {
            return new Promise((resolve, reject) => {
                const img = new Image()
                img.onload = () => resolve()
                img.onerror = () => reject(new Error('验证码图片加载失败'))
                img.src = this.captchaImageUrl
            })
        },
        async refreshCaptcha() {
            if (!this.selectedConfig) return
            try {
                await this.generateCaptcha(this.selectedConfig)
            } catch (error) {
                console.error('刷新验证码失败:', error)
                alert('刷新验证码失败，请重试')
            }
        },
        closeConfig() {
            this.selectedConfig = null
            this.configJson = ''
            this.curlCommand = ''
            this.httpRequest = ''
            this.captchaImageUrl = ''
            this.testCaptchaUrl = ''
            this.captchaId = ''
            this.testCaptchaId = ''
            this.validateCode = ''
            this.validateResult = null
        },
        generateTestCaptcha() {
            const timestamp = new Date().getTime()
            this.testCaptchaId = `test_${timestamp}`
            this.testCaptchaUrl = `captcha/demo?id=${encodeURIComponent(this.testCaptchaId)}&_t=${timestamp}`
            this.validateCode = ''
            this.validateResult = null
        },
        async validateCaptcha(isReusable) {
            if (!this.validateCode) {
                alert('请先输入验证码')
                return
            }

            try {
                let apiUrl
                if (isReusable) {
                    // 可重复校验 - 使用 validate2 接口（不删除验证码）
                    apiUrl = `captcha/validate2?id=${encodeURIComponent(this.testCaptchaId)}&code=${encodeURIComponent(this.validateCode)}`
                } else {
                    // 一次性校验 - 使用 validate 接口（验证后删除）
                    apiUrl = `captcha/validate?id=${encodeURIComponent(this.testCaptchaId)}&code=${encodeURIComponent(this.validateCode)}`
                }

                console.log('校验请求:', {
                    id: this.testCaptchaId,
                    code: this.validateCode,
                    url: apiUrl,
                    isReusable: isReusable
                })

                const response = await fetch(apiUrl)
                const result = await response.json()

                console.log('校验响应:', result)

                this.validateResult = {
                    success: result,
                    isReusable: isReusable,
                    url: window.location.origin + '/' + apiUrl,
                    response: JSON.stringify(result),
                    timestamp: new Date().toLocaleTimeString(),
                    requestId: this.testCaptchaId,
                    requestCode: this.validateCode
                }

            } catch (error) {
                console.error('校验失败:', error)
                this.validateResult = {
                    success: false,
                    isReusable: isReusable,
                    url: `captcha/validate${isReusable ? '2' : ''}`,
                    response: `Error: ${error.message}`,
                    timestamp: new Date().toLocaleTimeString(),
                    requestId: this.testCaptchaId,
                    requestCode: this.validateCode
                }
            }
        }
    },
})